<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>zTreeDemo</title>
    <link rel="stylesheet" href="plugins/ztree/css/zTreeStyle/zTreeStyle.css">
    <script src="plugins/ztree/js/jquery-1.4.4.min.js"></script>
    <script src="plugins/ztree/js/jquery.ztree.all-3.5.js"></script>
    <SCRIPT LANGUAGE="JavaScript">
        var zTreeObj;
        // zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）
        var setting = {
            data: {
                simpleData: {
                    enable: true,  //开启了简单json数据结构
                    idKey: "id",
                    pIdKey: "pid",
                    rootPId: 0
                }
            },
            check: {
                enable: true,  //开启复选框
                chkStyle: "checkbox"
            }

        };
        // zTree 的数据属性，深入使用请参考 API 文档（zTreeNode 节点数据详解）
        /*  var zNodes = [
              {name:"test1", open:true, children:[
                      {name:"test1_1"}, {name:"test1_2",open:true,
                          children:[{name:"test1_2_1"},{name:"test1_2_2"},{name:"test1_2_3"}]}]},
              {name:"test2", open:true, children:[
                      {name:"test2_1"}, {name:"test2_2",open:true,children:[{name:"test2_2_1"}]}]}
          ];*/
        var zNodes = [
            {id:"1",pid:"0",name:"test1" ,checked:true},
            {id:"2",pid:"0",name:"test2"},
            {id:"11",pid:"1",name:"test1_1"},
            {id:"12",pid:"1",name:"test1_2" ,checked:true},
            {id:"121",pid:"12",name:"test1_2_1",checked:true},
            {id:"122",pid:"12",name:"test1_2_2"},
            {id:"123",pid:"12",name:"test1_2_3"},
            {id:"21",pid:"2",name:"test2_1"},
            {id:"22",pid:"2",name:"test2_2"},
            {id:"221",pid:"22",name:"test2_2_1"}
        ];



        $(document).ready(function(){
            zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, zNodes);
            zTreeObj.expandAll(true); // 展开树形上的所有节点
        });


        function save() {
            let ids = "";
            // 获取勾选的树形节点，从节点中获取id
            var checkedNodes = zTreeObj.getCheckedNodes(true);
            // 把每个节点对象的id拼接成一个字符串传到后台
            for (let i = 0; i < checkedNodes.length; i++) {

                if(i==checkedNodes.length-1){
                    ids += checkedNodes[i].id;
                }else{
                    ids += checkedNodes[i].id+",";
                }
            }
            alert(ids);
        }
    </SCRIPT>
</head>
<body>
<button onclick="save()">保存</button>
<ul id="treeDemo" class="ztree"/>
</body>
</html>